package com.ticket.web.controller.yanchu;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.ticket.common.core.domain.entity.SysUser;
import com.ticket.common.core.domain.model.LoginUser;
import com.ticket.common.exception.base.BaseException;
import com.ticket.common.utils.StringUtils;
import com.ticket.framework.web.service.TokenService;
import com.ticket.system.domain.vo.CardUserInfoVO;
import com.ticket.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ticket.common.annotation.Log;
import com.ticket.common.core.controller.BaseController;
import com.ticket.common.core.domain.AjaxResult;
import com.ticket.common.enums.BusinessType;
import com.ticket.system.domain.YanchuMovieCard;
import com.ticket.system.service.IYanchuMovieCardService;
import com.ticket.common.core.page.TableDataInfo;

/**
 * 观演卡数据Controller
 * 
 * @author ruoyi
 * @date 2023-12-12
 */
@RestController
@RequestMapping("/system/card")
@Api("观演卡数据")
public class YanchuMovieCardController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(YanchuMovieCardController.class);
    @Autowired
    private IYanchuMovieCardService yanchuMovieCardService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysUserService sysUserService;


    @ApiOperation("pc观演卡数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardNum",value = "卡号",dataType = "String",dataTypeClass = String.class),
            @ApiImplicitParam(name = "amount",value = "面值",dataType = "String",dataTypeClass = String.class),
            @ApiImplicitParam(name = "keyName",value = "会员或者手机号",dataType = "String",dataTypeClass = String.class),
            @ApiImplicitParam(name = "status",value = "绑定状态0：待绑定；1：已绑定",dataType = "int",dataTypeClass = Integer.class),
    })
    @PreAuthorize("@ss.hasPermi('system:card:list')")
    @GetMapping("/list")
    public TableDataInfo list(Long batchId,String cardNum,String amount,String keyName,Integer status)
    {
        startPage();
        List<YanchuMovieCard> list = yanchuMovieCardService.selectYanchuMovieCardByList(batchId,cardNum,amount,keyName,status);
        if (!CollectionUtils.isEmpty(list)){
            List<Long> userIds = Lists.newArrayList();
            userIds.addAll(list.stream().map(YanchuMovieCard::getCreatId).collect(Collectors.toList()));
            userIds.addAll(list.stream().map(YanchuMovieCard::getActiveId).collect(Collectors.toList()));
            userIds.addAll(list.stream().map(YanchuMovieCard::getBindId).collect(Collectors.toList()));
            List<CardUserInfoVO> cardUserInfos = sysUserService.getUserNameByIds(userIds);
            if (!CollectionUtils.isEmpty(cardUserInfos)){
                list.forEach(y ->{
                    cardUserInfos.forEach(c ->{
                        if (y.getCreatId().equals(c.getUserId())){
                            y.setCreatName(c.getUserName());
                        }
                        if (null != y.getActiveId() && y.getActiveId().equals(c.getUserId())){
                            y.setActiveName(c.getUserName());
                        }
                        if (null != y.getBindId() && y.getBindId().equals(c.getUserId())){
                            y.setBindName(c.getUserName());
                        }
                    });
                });
            }
        }
        return getDataTable(list);
    }

    @ApiOperation("导出观演卡")
    @PreAuthorize("@ss.hasPermi('system:card:export')")
    @Log(title = "观演卡批次信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,Long batchId,String cardNum,String cardIds)
    {
        List<Long> carId = Lists.newArrayList();
        if (StringUtils.isNotEmpty(cardIds)){
            carId = Arrays.stream(cardIds.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        }else {
            List<YanchuMovieCard> cards = yanchuMovieCardService.selectYanchuMovieCardByList(batchId, cardNum, null, null,null);
            if (!CollectionUtils.isEmpty(cards)){
                carId = cards.stream().map(YanchuMovieCard::getId).collect(Collectors.toList());
            }
        }
        yanchuMovieCardService.export(carId,response);
    }

    @ApiOperation("小程序登录用户绑定观演卡")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardNum",value = "卡号",required = true,dataTypeClass = String.class,dataType = "String"),
            @ApiImplicitParam(name = "cardPasswoed",value = "密码",required = true,dataTypeClass = String.class,dataType = "String"),
    })
    @PostMapping("/bindMovie")
    public AjaxResult bindMovie(@RequestParam String cardNum,@RequestParam String cardPasswoed, HttpServletRequest request){
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (null == loginUser){
            throw new BaseException("为获取用户信息,请重新登录。");
        }
        SysUser user = loginUser.getUser();
        log.info("bindMovie -->user:{}", JSONObject.toJSONString(user));
        return toAjax(yanchuMovieCardService.bindMovie(cardNum,cardPasswoed,user.getNickName(),user.getUserId(),user.getPhonenumber()));
    }

    @ApiOperation("小程序登录用户获取观演卡列表数据")
    @ApiImplicitParam(name = "type",value = "1：可用观演卡；2：不可用观演卡数据",dataType = "int",dataTypeClass = Integer.class,required = true)
    @GetMapping("/mobileCardList")
    public AjaxResult mobileCardList(HttpServletRequest request,@RequestParam Integer type){
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (null == loginUser){
            throw new BaseException("为获取用户信息,请重新登录。");
        }
        return success(yanchuMovieCardService.mobileCardList(loginUser.getUser().getUserId(),type));
    }
}
